<template>
	<view class="main">
		<uni-icons @click="onFabClick" class="setting-icon" type="gear-filled" size="40" color="#ffffff"></uni-icons>
		
		<div style="text-align: right;">
			<button v-if="global.option.type == 4"  @click="generateSame()" size="mini" class="uni-ml-2">生成错题卷</button>
		</div>
		<div class="table">
			<uni-table border stripe emptyText="暂无更多数据">
				<!-- 表头行 -->
				<uni-tr>
					<uni-th align="center" width="120">试卷名称</uni-th>
					<!-- <uni-th align="center" width="60">学科</uni-th> -->
					<uni-th align="center" width="50">难度</uni-th>
					<uni-th align="center" width="50">满分</uni-th>
					<uni-th align="center" width="140">操作</uni-th>
				</uni-tr>
				<!-- 表格数据行 -->
				<uni-tr
				v-for="row in paperList"
				:key="row.id"
				>
					<uni-td>{{row.name}}</uni-td>
					<!-- <uni-td>{{row.subject}}</uni-td> -->
					<uni-td>
						<template v-if="global.option.type != 4">
								{{row.difficulty}}星
						</template>
					</uni-td>
					<uni-td>
					<template v-if="global.option.type != 4">
						{{row.fullScore}}
					</template>
					</uni-td>
					<uni-td>
						<button @click="view(row)" size="mini">查看</button>
						<button v-if="row.pdfUrl" @click="exportPDF(row)" size="mini" class="uni-ml-2">导出(带答案)</button>
						<!--
						<button v-if="global.option.type == 6" @click="generateSame(row)" size="mini" class="uni-ml-2">生成模拟试卷</button>-->
						<button v-if="global.option.type == 4" @click="delErrTopic(row)" size="mini" class="uni-ml-2">删除</button>
					</uni-td>
				</uni-tr>
			</uni-table>
		</div>
		<uni-pagination class="uni-pagination" v-model="pageConfig.current" :total="pageConfig.total" :pageSize="pageConfig.limit" prev-text="前一页" next-text="后一页" title="分页"></uni-pagination>
		<!-- 筛选弹窗 -->
		<uni-drawer ref="drawerRef" mode="right" :width="300">
			<div class="uni-pa-4">
				<uni-forms ref="formRef" :modelValue="formData" label-width="70px">
					<uni-forms-item label="试卷名称" name="name">
						<uni-easyinput v-model="formData.name" placeholder="请输入试卷名称" />
					</uni-forms-item>
					<uni-forms-item label="难度" name="verifyCode">
						<uni-easyinput type="number" v-model="formData.difficulty" placeholder="试卷难度" />
					</uni-forms-item>
				</uni-forms>
			</div>
			<div class="footer">
				<button @click="onSureFilter">确定</button>
			</div>
		</uni-drawer>
	</view>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import request from '../../utils/request';
import { onLoad } from "@dcloudio/uni-app";
import { navigateTo } from '../../utils/utils';

const paperList = ref<any[]>([]);

const drawerRef = ref(null);

const formData = reactive({
	categoryId: '',
	name: '',
	difficulty: '',
	paperStatus: 1, // 0未上架,1上架,2已下架
});

const global = reactive({
	option: {
		type: 1
	},
});

// 分页配置
const pageConfig = reactive({
    limit: 20,
    current: 1,
    total: 0
});

const getPaperList = async () => {
	try{
		const { records, total } = await request({
			method: 'POST',
			url: '/app/member-paper/list',
			contentTypeIsForm: false,
			data: {
				...formData,
				limit: pageConfig.limit,
				page: pageConfig.current,
				paperType: global.option.type
			}
		});
		console.log('records: ', records);
		paperList.value = records;
		// paperList.value = [...records,...records,...records,...records];
		pageConfig.total = total;
	} catch(e) {
		//TODO handle the exception
	}
};

// 点击确定筛选
const onSureFilter = () => {
	drawerRef.value?.close();
	pageConfig.current = 1;
	pageConfig.limit = 20;
	pageConfig.total = 0;
	getPaperList();
};

// 点击筛选
const onFabClick = () => {
	drawerRef.value?.open();
};

// 点击查看
const view = (row: any) => {
	
	console.log(row.id);
	let url = '/pages/paperView/paperView';
	if (global.option.type == 4){
		
		url = '/pages/paperView/paperViewError';
	}
	console.log(url);
	navigateTo(
	{
		url: url,
		query: {
			id: row.id
		}
	});
};

// 点击导出PDF
const exportPDF = (row: any) => {
	
	console.log(row.pdfUrl);
	
	uni.showLoading({
	title: '正在下载'
	});
	// 本地路径开头使用file://，跟上手机文件本地目录storage/emulated/0，
	// 这时用户文件管理器能看到的了，之后创建 连信 作为文件夹，
	// 后缀是用于文件命名和格式修改，大家可以使用变量。
	var url = row.pdfUrl;
	let dtask = plus.downloader.createDownload(url, {
		filename: "file://storage/emulated/0/pite/"  //利用保存路径，实现下载文件的重命名
	},(d, status)=> {
		//d为下载的文件对象
		if (status == 200) {
			uni.hideLoading();
			uni.showToast({
				icon: 'success',
				mask: true,
				title: "下载成功", //保存路径
				duration: 3000,
			});
			//下载成功,d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径
			//let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
			setTimeout(()=>{
				
				plus.runtime.openFile(d.filename); //选择软件打开文件
			},1500)
		} else {
			//下载失败
			uni.hideLoading();
			plus.downloader.clear(); //清除下载任务
			uni.showToast({
				icon:'fail',
				mask:true,
				title: '下载失败，请稍后重试',
			});
		}
	})
	dtask.start();

	/**
	uni.downloadFile({
		url: row.pdfUrl,
		fail: () => {
			uni.showToast({
				title: '下载失败',
				icon: 'fail'
			});
		},
		success: () => {
			uni.showToast({
				title: '下载成功',
				icon: 'success'
			});
		}
	});**/
};

// 点击生成错题试卷
const generateSame = async () => {
	const id = await request({
		url: "/app/member-paper/generateSame",
		method: 'POST',
		contentTypeIsForm: true,
		showLoading: {},
		errorToast: true
	});
	if(id != 0){
		navigateTo({
			url: '/pages/paperView/paperView',
			query: {
				id
			},
		});
	} else {
		uni.showToast({
			title: '没有符合条件的数据生成',
			icon: 'error'
		});
		
	}
	
};

// 点击删除错题试卷
const delErrTopic = async (row: any) => {
	try{
		await uni.showModal({
			title: '提示',
			content: '确定删除?',
			showCancel: true,
			cancelText: '取消'
		});
		await request({
			url: "/app/member-paper/delete",
			method: 'POST',
			contentTypeIsForm: true,
			showLoading: {},
			errorToast: true,
			data: {
				id: row.id
			}
		});
		uni.showToast({
			title: '删除成功',
			icon: 'success'
		});
		paperList.value.splice(paperList.value.findIndex(item => item.id == row.id), 1);
	} catch (e) {
		//TODO handle the exception
	}
};

onMounted(() => {
	getPaperList();
});

onLoad((option) => {
	// console.log(option);
	global.option.type = option.type;
});
</script>

<style lang="scss" scoped>
@import './paperList.scss';
</style>
